package admin

import (
	"context"
	"sort"

	"server/internal/svc"
	"server/internal/types"
	"server/models"
	"server/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type PermissionRoutesLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewPermissionRoutesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PermissionRoutesLogic {
	return &PermissionRoutesLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PermissionRoutesLogic) PermissionRoutes() (resp []types.PermissionRoutesResp, err error) {
	// 获取所有权限数据
	datas := make([]models.Permission, 0)
	tx := utils.Db.Model(&models.Permission{}).Order("sort ASC,id ASC")
	utils.TxFind(tx, &datas)
	if len(datas) == 0 {
		return []types.PermissionRoutesResp{}, nil
	}
	// logx.Infof("获取权限列表成功: %v", datas)
	// roleActions := make([]string, 0)
	// if req.RoleID > 0 {
	// 	// 检查角色是否存在
	// 	role := &models.AdminRole{}
	// 	if !utils.GetDataById(req.RoleID, role) {
	// 		logx.Errorf("角色不存在: %v", err)
	// 		return nil, errors.New("角色不存在")
	// 	}
	// 	roleActions = strings.Split(role.Permissions, ",")
	// }

	// 构建权限树
	permissionMap := make(map[uint][]models.Permission)
	for _, p := range datas {
		// 检查该权限是否在角色对应的动作中
		// if req.RoleID > 0 {
		// 	if slices.Contains(roleActions, p.Perm) {
		// 		permissionMap[p.ParentID] = append(permissionMap[p.ParentID], p)
		// 	}
		// } else {
		permissionMap[p.ParentID] = append(permissionMap[p.ParentID], p)
		// }

	}

	// 生成树形结构
	var buildTree func(parentID uint) []types.PermissionRoutesResp
	buildTree = func(parentID uint) []types.PermissionRoutesResp {
		var nodes []types.PermissionRoutesResp
		children, exists := permissionMap[parentID]
		if exists {
			// 按排序字段排序
			sort.Slice(children, func(i, j int) bool {
				return children[i].Sort < children[j].Sort
			})
			for _, child := range children {
				params := make(map[string]any)
				if child.Params.String() != "" {
					utils.JsonToStruct(child.Params.String(), &params)
				} else {
					params = nil
				}
				// meta := map[string]any{
				// 	"title":      child.Name,
				// 	"icon":       child.Icon,
				// 	"alwaysShow": child.AlwaysShow,
				// 	"hidden":     child.Hidden,
				// 	"keepAlive":  child.KeepAlive,
				// 	"params":     params,
				// }
				meta := types.PermissionRoutesMeta{
					Title:      child.Name,
					Icon:       child.Icon,
					Hidden:     child.Hidden,
					KeepAlive:  child.KeepAlive,
					AlwaysShow: child.AlwaysShow,
					Params:     params,
				}
				node := types.PermissionRoutesResp{
					Perm:      child.Perm,
					Path:      child.RoutePath,
					Component: child.Component,
					Redirect:  child.Redirect,
					Name:      child.RouteName,
					Meta:      meta,
				}
				children := buildTree(child.ID)
				if len(children) > 0 {
					node.Children = children
				} else {
					node.Meta.AlwaysShow = false
					node.Children = nil
					// node.Children = []types.PermissionRoutesResp{}
				}
				nodes = append(nodes, node)
			}
		}
		return nodes
	}

	// 从根节点开始构建树
	rootNodes := buildTree(0)

	return rootNodes, nil
}
